package com.jic.market.impl;

import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.market.common.base.MarketBaseService;
import com.jic.market.common.exception.MarketErrorCodeEnum;
import com.jic.market.common.exception.MarketException;
import com.jic.market.entity.Material;
import com.jic.market.entity.MaterialCategory;
import com.jic.market.mapper.MaterialCategoryMapper;
import com.jic.market.mapper.MaterialMapper;
import com.jic.market.request.*;
import com.jic.market.response.*;
import com.jic.market.service.MaterialCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 素材分类表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-02-27 04:39:42
 */
@Service
public class MaterialCategoryServiceImpl extends MarketBaseService implements MaterialCategoryService {

    @Autowired
    private MaterialCategoryMapper materialCategoryMapper;
    @Autowired
    private MaterialMapper materialMapper;
    @Override
    public RestResult<PageResult<MaterialCategoryFirstInfo>> queryPage(MaterialCategoryQueryRequest request) {
        return executeQuery(() -> {
            AdminOperate adminOperate = request.getAdminOperate();
            //一级查询
            List<MaterialCategoryFirstInfo> firstInfoList = new ArrayList<>();
            MaterialCategory materialCategoryFirst = new MaterialCategory();
            materialCategoryFirst.setCategoryLevel(1);
            materialCategoryFirst.setIsDelete(false);
            // 权限需要
            if(null != adminOperate){
                materialCategoryFirst.setDeptId(adminOperate.getDeptId());
                materialCategoryFirst.setDeptType(adminOperate.getDeptType().getCode());
            }

            List<MaterialCategory> firstCategoryList = materialCategoryMapper.query(materialCategoryFirst);
            if (null != firstCategoryList && !firstCategoryList.isEmpty()) {
                for (MaterialCategory category1 : firstCategoryList) {
                    MaterialCategoryFirstInfo firstInfo = new MaterialCategoryFirstInfo();
                    MaterialCategoryInfo firstBaseInfo = new MaterialCategoryInfo();
                    BeanUtils.copyProperties(category1, firstBaseInfo);
                    firstInfo.setCategoryInfo(firstBaseInfo);
                    //二级查询
                    List<MaterialCategorySecondInfo> secondInfoList = new ArrayList<>();
                    MaterialCategory materialCategorySecond = new MaterialCategory();
                    materialCategorySecond.setCategoryLevel(2);
                    materialCategorySecond.setParentCategoryId(category1.getId());
                    materialCategorySecond.setIsDelete(false);
                    List<MaterialCategory> secondCategoryList = materialCategoryMapper.query(materialCategorySecond);
                    if (null != secondCategoryList && !secondCategoryList.isEmpty()) {
                        for (MaterialCategory category2 : secondCategoryList) {
                            MaterialCategorySecondInfo secondInfo = new MaterialCategorySecondInfo();
                            MaterialCategoryInfo secondBaseInfo = new MaterialCategoryInfo();
                            BeanUtils.copyProperties(category2, secondBaseInfo);
                            secondInfo.setCategoryInfo(secondBaseInfo);
                            //三级查询
                            List<MaterialCategoryThirdInfo> thirdInfoList = new ArrayList<>();
                            MaterialCategory materialCategoryThird = new MaterialCategory();
                            materialCategoryThird.setCategoryLevel(3);
                            materialCategoryThird.setParentCategoryId(category2.getId());
                            materialCategoryThird.setIsDelete(false);
                            List<MaterialCategory> thirdCategoryList = materialCategoryMapper.query(materialCategoryThird);
                            if (null != thirdCategoryList && !thirdCategoryList.isEmpty()) {
                                for (MaterialCategory category3 : thirdCategoryList) {
                                    MaterialCategoryThirdInfo thirdInfo = new MaterialCategoryThirdInfo();
                                    MaterialCategoryInfo thirdBaseInfo = new MaterialCategoryInfo();
                                    BeanUtils.copyProperties(category3, thirdBaseInfo);
                                    thirdInfo.setCategoryInfo(thirdBaseInfo);
                                    thirdInfoList.add(thirdInfo);
                                }
                                secondInfo.setInfoList(thirdInfoList);
                            }
                            secondInfoList.add(secondInfo);
                        }
                        firstInfo.setInfoList(secondInfoList);
                    }
                    firstInfoList.add(firstInfo);
                }
            }
            //计算总条数
            long count = materialCategoryMapper.queryPageCount(materialCategoryFirst);
            PageResult pageResult = new PageResult();
            pageResult.setRows(firstInfoList);
            pageResult.setTotal(count);
            return pageResult;
        });
    }

    @Override
    public RestResult<Long> add(MaterialCategoryAddRequest request) {
        return executeQuery(() -> {
            AdminOperate adminOperate = request.getAdminOperate();

            MaterialCategory materialCategory = new MaterialCategory();
            BeanUtils.copyProperties(request, materialCategory, "deptId", "merchantId", "storeId");
            materialCategory.setIsDelete(Boolean.FALSE);
            if(null != adminOperate){
                //权限信息
                materialCategory.setDeptId(adminOperate.getDeptId());
                materialCategory.setDeptType(adminOperate.getDeptType().getCode());
                //创建信息
                materialCategory.setCreator(adminOperate.getOperator());
                materialCategory.setCreateName(adminOperate.getOperateName());
                materialCategory.setCreateTime(new Date());
                //更新信息
                materialCategory.setUpdator(adminOperate.getOperator());
                materialCategory.setUpdateName(adminOperate.getOperateName());
            }

            materialCategory.setUpdateTime(new Date());
            long flag = materialCategoryMapper.insert(materialCategory);
            return flag;
        });
    }

    @Override
    public RestResult<Long> edit(MaterialCategoryEditRequest request) {
        return executeQuery(() -> {
            AdminOperate adminOperate = request.getAdminOperate();

            MaterialCategory materialCategory = new MaterialCategory();
            BeanUtils.copyProperties(request, materialCategory, "deptId", "merchantId", "storeId");
            //更新信息
            if(null != adminOperate){
                materialCategory.setUpdator(adminOperate.getOperator());
                materialCategory.setUpdateName(adminOperate.getOperateName());
            }
            materialCategory.setUpdateTime(new Date());
            long flag = materialCategoryMapper.update(materialCategory);
            return flag;
        });
    }

    @Override
    public RestResult<Long> delete(MaterialCategoryDeleteRequest request) {
        return executeQuery(() -> {
            AdminOperate adminOperate = request.getAdminOperate();

            //如果有关联数据，则不能删除
            MaterialCategory materialCategory = materialCategoryMapper.queryByPrimaryKey(request.getId());
            if(null == materialCategory){
                return 0L;
            }
            // 三级
            if(materialCategory.getCategoryLevel().equals(3)){
                List<Long> ids = new ArrayList<>();
                ids.add(request.getId());
                // 判断这些关联的3级id下是否有素材数据
                hasMaterial(ids);
                deleteCategoryByIds(ids, adminOperate);
            }
            // 二级
            else if(materialCategory.getCategoryLevel().equals(2)){
                // 查询出关联的3级id
                List<Long> parentIds = new ArrayList<>();
                parentIds.add(request.getId());
                List<Long> ids = materialCategoryMapper.queryIdsByParentCategoryIds(parentIds);
                if(null == ids || ids.isEmpty()){
                    deleteCategoryByIds(parentIds, adminOperate);
                    return 0L;
                }else{
                    throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, "请先删除下级分类");
                }
            }
            // 一级
            else if(materialCategory.getCategoryLevel().equals(1)){
                // 查询出关联的2级id
                List<Long> parentIds = new ArrayList<>();
                parentIds.add(request.getId());
                List<Long> secondIds = materialCategoryMapper.queryIdsByParentCategoryIds(parentIds);
                if(null == secondIds || secondIds.isEmpty()){
                    deleteCategoryByIds(parentIds, adminOperate);
                    return 0L;
                }else{
                    throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, "请先删除下级分类");
                }
            }
            return 0L;
        });
    }

    private void hasMaterial(List<Long> categoryIds){
        if(null == categoryIds && categoryIds.isEmpty()){
            return;
        }
        // 判断这些关联的3级id下是否有素材数据
        List<Material> materialList = materialMapper.queryByCategoryIds(categoryIds);
        if(!materialList.isEmpty()){
            throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, "有关联的素材数据，不能删除");
        }
    }

    private long deleteCategoryByIds(List<Long> ids, AdminOperate adminOperate){
        for(Long id : ids){
            MaterialCategory materialCategory = new MaterialCategory();
            materialCategory.setId(id);
            materialCategory.setIsDelete(true);
            //更新信息
            if(null != adminOperate){
                materialCategory.setUpdator(adminOperate.getOperator());
                materialCategory.setUpdateName(adminOperate.getOperateName());
            }
            materialCategory.setUpdateTime(new Date());
            materialCategoryMapper.update(materialCategory);
        }
        return 0;
    }

    @Override
    public RestResult<MaterialCategoryTreeResponse> queryTree(MaterialCategoryTreeRequest request) {
        return executeQuery(() -> {
            AdminOperate adminOperate = request.getAdminOperate();

            MaterialCategoryTreeResponse response = new MaterialCategoryTreeResponse();
            //查询平台树
            List<MaterialCategoryFirstTreeInfo> firstTreeInfoList = getMaterialCategoryFirstTreeInfos(179L);//母平台固定组织id
            if (adminOperate != null && DeptTypeEnums.OPERATION_PLATFORM.getCode().equals(adminOperate.getDeptType().getCode())) {
                response.setDeptTreeCanEdit(true);
            }else {
                response.setDeptTreeCanEdit(false);
            }
            response.setDeptTreeList(firstTreeInfoList);
            //查询本地树，平台登录的时候不用查本地树
            if (adminOperate != null && !DeptTypeEnums.OPERATION_PLATFORM.getCode().equals(adminOperate.getDeptType().getCode())) {
                List<MaterialCategoryFirstTreeInfo> localTreeInfoList = getMaterialCategoryFirstTreeInfos(adminOperate.getDeptId());
                response.setLocalTreeCanEdit(true);
                response.setLocalTreeList(localTreeInfoList);
            }
            return response;
        });
    }

    private List<MaterialCategoryFirstTreeInfo> getMaterialCategoryFirstTreeInfos(Long deptId) {
        //一级
        MaterialCategory materialCategory1 = new MaterialCategory();
        if (null != deptId) {
            materialCategory1.setDeptId(deptId);
        }
        materialCategory1.setCategoryLevel(1);
        materialCategory1.setIsDelete(false);
        materialCategory1.setIsShow(true);
        List<MaterialCategory> firstCategoryList = materialCategoryMapper.query(materialCategory1);
        if (null != firstCategoryList && !firstCategoryList.isEmpty()) {
            List<MaterialCategoryFirstTreeInfo> firstTreeInfoList = new ArrayList<>();
            for (MaterialCategory category1 : firstCategoryList) {
                MaterialCategoryFirstTreeInfo firstTreeInfo = new MaterialCategoryFirstTreeInfo();
                BeanUtils.copyProperties(category1, firstTreeInfo);
                //二级
                List<MaterialCategorySecondTreeInfo> secondTreeInfoList = new ArrayList<>();
                MaterialCategory materialCategory2 = new MaterialCategory();
                materialCategory2.setCategoryLevel(2);
                materialCategory2.setParentCategoryId(category1.getId());
                materialCategory2.setIsDelete(false);
                materialCategory2.setIsShow(true);
                List<MaterialCategory> secondCategoryList = materialCategoryMapper.query(materialCategory2);
                if (null != secondCategoryList && !secondCategoryList.isEmpty()) {
                    for (MaterialCategory category2 : secondCategoryList) {
                        MaterialCategorySecondTreeInfo secondTreeInfo = new MaterialCategorySecondTreeInfo();
                        BeanUtils.copyProperties(category2, secondTreeInfo);
                        //三级
                        List<MaterialCategoryThirdTreeInfo> thirdTreeInfoList = new ArrayList<>();
                        MaterialCategory materialCategory3 = new MaterialCategory();
                        materialCategory3.setCategoryLevel(3);
                        materialCategory3.setParentCategoryId(category2.getId());
                        materialCategory3.setIsDelete(false);
                        materialCategory3.setIsShow(true);
                        List<MaterialCategory> thirdCategoryList = materialCategoryMapper.query(materialCategory3);
                        if (null != thirdCategoryList && !thirdCategoryList.isEmpty()) {
                            for (MaterialCategory category3 : thirdCategoryList) {
                                MaterialCategoryThirdTreeInfo thirdTreeInfo = new MaterialCategoryThirdTreeInfo();
                                BeanUtils.copyProperties(category3, thirdTreeInfo);
                                thirdTreeInfoList.add(thirdTreeInfo);
                            }
                        }
                        secondTreeInfo.setTreeInfoList(thirdTreeInfoList);
                        secondTreeInfoList.add(secondTreeInfo);
                    }
                }
                firstTreeInfo.setTreeInfoList(secondTreeInfoList);
                firstTreeInfoList.add(firstTreeInfo);
            }
            return firstTreeInfoList;
        }
        return null;
    }


}
